const { Server } = require('socket.io');
const { v4: uuidv4 } = require('uuid');
const { ConversationModel } = require('../model/model');

// AI回复函数保持不变
function getLocalAIResponse(message) {
    const responses = {
        '你好': '你好！我是AI助手，很高兴为您服务。',
        '在吗': '在的，请问有什么可以帮您？',
        '怎么': '这是一个很好的问题，让我来为您解答。',
        '为什么': '这个问题的原因可能有以下几点...',
        '谢谢': '不客气，很高兴能帮到您。',
        '再见': '再见，祝您有愉快的一天！'
    };

    for (const key in responses) {
        if (message.includes(key)) {
            return responses[key];
        }
    }
    return '我明白您的意思，请告诉我更多细节，这样我能更好地帮助您。';
}

function setupSocket(server) {
    const io = new Server(server, {
        cors: {
            origin: ["http://localhost:8080", "http://localhost:8081"],
            methods: ["GET", "POST"],
            credentials: true
        }
    });

    // 存储在线客服
    const onlineServices = new Set();
    // 存储等待队列
    const waitingQueue = new Map();

    io.on('connection', (socket) => {
        console.log('新连接建立，ID:', socket.id);

        // 客服连接处理
        socket.on('service_connect', () => {
            console.log('客服连接:', socket.id);
            onlineServices.add(socket.id);
            
            // 检查等待队列
            if(waitingQueue.size > 0) {
                const [customerId, customerInfo] = waitingQueue.entries().next().value;
                io.to(socket.id).emit('new_customer', {
                    customerId,
                    visitorInfo: customerInfo
                });
                io.to(customerId).emit('service_connected');
                waitingQueue.delete(customerId);
            }
        });

        // 转人工请求处理
        socket.on('transfer_to_service', async (uniqueId) => {
            try {
                // 先检查这个访客是否已经有正在进行的会话
                const existingConversation = await ConversationModel.findOne({
                    userId: uniqueId,
                    status: { $in: ['waiting', 'in_service'] }
                });

                if (!existingConversation) {
                    // 创建新会话
                    const newConversation = new ConversationModel({
                        conversationId: uuidv4(),
                        userId: uniqueId,
                        status: 'in_service',
                        customerName: '大客户',
                        startTime: new Date(),
                        messages: [
                            {
                                content: "您好我是客服007，请问有什么可以帮您？",
                                type: 'service',    // service=客服发的消息
                                timestamp: new Date()
                            },
                            {
                                content: "我需要咨询一些问题",
                                type: 'user',       // user=访客发的消息
                                timestamp: new Date()
                            }
                        ]
                    });
                    await newConversation.save();
                    console.log('已创建新会话:', newConversation.conversationId);
                } else {
                    console.log('用户已有进行中的会话:', existingConversation.conversationId);
                }
            } catch (error) {
                console.error('创建会话失败:', error);
            }
        });

        // 聊天消息处理
        socket.on('chat message', async (msg) => {
            console.log('收到用户消息:', msg);
            
            try {
                if(msg.toUser) {
                    // 客服发送给特定用户的消息
                    io.to(msg.toUser).emit('chat message', {
                        content: msg.content,
                        user: 'service',
                        timestamp: new Date().toLocaleTimeString()
                    });
                } else {
                    // AI回复
                    const aiResponse = getLocalAIResponse(msg.content);
                    socket.emit('chat message', {
                        content: aiResponse,
                        user: 'ai',
                        timestamp: new Date().toLocaleTimeString()
                    });
                }
            } catch (error) {
                console.error('处理消息错误:', error);
                socket.emit('chat message', {
                    content: "抱歉，我遇到了一些问题，请稍后再试。",
                    user: 'ai',
                    timestamp: new Date().toLocaleTimeString()
                });
            }
        });

        // 断开连接处理
        socket.on('disconnect', () => {
            console.log('连接断开:', socket.id);
            
            if (onlineServices.has(socket.id)) {
                // 客服断开
                onlineServices.delete(socket.id);
                io.emit('service_disconnected');
            } else {
                // 访客断开
                waitingQueue.delete(socket.id);
                io.emit('customer_disconnected', { customerId: socket.id });
            }
        });
    });

    return io;
}

module.exports = setupSocket;